package com.fjec.devops.schedule.handler;

import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.okhttp.OkHttp;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.wx.WxAccessTokenHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
//@Component
public class AccessTokenHandler extends BaseScheduleHandler {
    private static String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx525f2c0776872dc2&secret=52c3307f41a85e304b3579c7cfe1a7ad";

    @Resource
    private WxAccessTokenHelper wxAccessTokenHelper;

    public String handle() {
        String result;
        try {
            String accessToken = wxAccessTokenHelper.cacheAccessToken();
            result = String.format("Get accessToken success![%s]", accessToken);
        } catch (Exception ex) {
            result = String.format("Get accessToken error: [%s], TraceId: [%s]."
                    , ex.getMessage(), this.error(ex));
        }
        return result;
    }

//    @Autowired
//    private OkHttp okHttp;

//    @CachePut(cacheNames = "c_30", key = "'fjec:wechat:access_token'")
//    public String putAccessToken() {
//        return doGetAccessToken();
//    }
//
//    @Cacheable(cacheNames = "c_30", key = "'fjec:wechat:access_token'")
//    public String getAccessToken() {
//        return doGetAccessToken();
//    }
//
//    public String doGetAccessToken() {
//        String res = okHttp.get(tokenUrl);
//        Map<String, Object> resMap = JsonUtil.jsonToMap(res);
//        Integer errCode = MapUtils.getInteger(resMap, "errcode");
//        if (errCode != null && errCode != 0) {
//            log.error("Get access token error:[%s]", res);
//            BizException ex = new BizException(EnumSysCode.ERR_3018.getCode(), res);
//            String guid = this.error(ex);
//            throw ex;
//        }
//        String token = MapUtils.getString(resMap, "access_token");
//        return token;
//    }
}
